package com.ztesoft.book.admin.config.captcha;

import com.google.code.kaptcha.Producer;
import com.ztesoft.book.common.constant.Constant;
import com.ztesoft.book.common.utils.exception.ServiceException;
import com.ztesoft.book.common.utils.redis.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;

/**
 * @Description 验证码工具类
 * @Author YangFan
 * @Date 2021-06-22 17:27
 */
@Component
public class CaptchaUtil {


    private static Producer producer;

    @Autowired
    public void setProducer(Producer producer) {
        setProducerValue(producer);
    }
    public static void setProducerValue(Producer producer) {
        CaptchaUtil.producer = producer;
    }


    public static BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new ServiceException("验证码UUID不能为空");
        }
        // 生成文字验证码
        String code = producer.createText();
        // 验证码信息写入redis缓存（有效时间5分钟）
        RedisUtils.set("captcha:" + uuid, code, 5 * 60);
        return producer.createImage(code);
    }

    public static boolean validate(String uuid, String code) {
        String cacheCode = "";
        if (RedisUtils.exists(Constant.PREFIX_CAPTCHE + uuid)) {
            cacheCode = RedisUtils.get(Constant.PREFIX_CAPTCHE + uuid).toString();
        }
        if (StringUtils.isBlank(cacheCode)) {
            return false;
        }
        if (cacheCode.equalsIgnoreCase(code)) {
            return true;
        }
        return false;
    }

}
